<template>
  <div class="button-container">
    <el-button v-for="(segmentName, segmentIndex) in ['第一段', '第二段', '第三段', '第四段']" :key="segmentIndex" type="primary"
      @click="showDialog(segmentIndex)">
      {{ segmentName }}
    </el-button>
    <el-button type="warning" class="申报规则" @click="showRulesDialog">申报规则</el-button>
  </div>
  <div v-if="showPopup">
    <el-table :data="selectedGroupData" style="width: 100%; border: 1px solid #dcdcdc;">
      <el-table-column label="分值编码" width="180" align="center">
        <template #default="scope">
          <div v-for="row in [scope.row]" :key="row.id" class="centered-content">
            <span>{{ row.score ? `${row.score}` : '' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="left">
        <template #default="scope">
          <div v-for="row in scope" :key="row.id" style="display: flex; flex-wrap: wrap; gap: 10px;">
            <span>{{ row.content }}{{ row.code ? `(${row.code})` : '' }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="closeRulesDialog" class="close-popup-btn">关闭</el-button>
  </div>
  <el-dialog v-for="(dialog, dialogIndex) in dialogs" :key="dialogIndex" v-model="dialog.visible" :title="dialog.title">
    <el-autocomplete v-model="preFilledData[dialogIndex].code" :fetch-suggestions="querySearch" placeholder="请选择代码"
      @select="item => handleSelect(item, dialogIndex)" @blur="() => checkCodeRisk(dialogIndex)"
      :dialog-index="dialogIndex">
      <template #default="{ item }">
        <div>{{ item }}</div>
      </template>
    </el-autocomplete>
    <i class="el-icon-warning"
      v-if="preFilledData[dialogIndex].code && !codes.includes(preFilledData[dialogIndex].code)"
      style="color: red; display: block; margin-top: 10px;">
      编码不在预设列表中，有风险
    </i>
    <el-autocomplete v-model="preFilledData[dialogIndex].score" placeholder="分数（自动更新）"
      :disabled="!preFilledData[dialogIndex].code">
      <el-option :label="getScoreByCode(preFilledData[dialogIndex].code)"
        :value="getScoreByCode(preFilledData[dialogIndex].code)" />
    </el-autocomplete>
    <span class="dialog-footer">
      <el-button @click="closeDialog(dialogIndex)">取消</el-button>
      <el-button type="primary" @click="saveData(dialogIndex)">确定</el-button>
    </span>
  </el-dialog>

  <div v-if="!showPopup">
    <div v-for="(segmentData, segmentIndex) in segmentDataGroups" :key="segmentIndex" class="segment-container"
      style="display: flex;">
      <h3 style="font-size: 15px;">{{ getSegmentNameByIndex(segmentIndex) }}:</h3>
      <div v-for="(item, itemIndex) in segmentData" :key="itemIndex" class="submitted-item"
        style="margin:0 0 15px 10px;">
        <p>序号:{{ itemIndex + 1 }}</p> <!-- 使用段内索引 + 1 作为序号 -->
        <p>编码:{{ item.code }}</p>
        <p>分数:{{ item.score }}</p>
        <div>
          <el-popover placement="top-start" title="内容" :width="200" trigger="hover" :content="item.content">
            <template #reference>
              <p>内容：{{ replaceCharacters(item.content) }}</p> <!-- 添加内容渲染 -->
            </template>
          </el-popover>
        </div>
        <el-button type="danger" @click="deleteData(segmentIndex, itemIndex)"
          style="height: 25px; width: 40px;">删除</el-button>
      </div>
    </div>
    <el-button type="primary" @click="soloback">返回上一步</el-button>
    <el-button type="primary" @click="submitAllData" style="float: right;">提交所有数据</el-button>
  </div>
</template>

<script setup>
import { useTeamStore } from '../store/teamgroupid.js';
import { ref, watch, onMounted } from 'vue';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';
const route = useRoute();
const router = useRouter();

const routineid = route.query.routineid;

const teamStore = useTeamStore();

const projectname = ref();

const addappliction = ref('');

const teamId = teamStore.teamGroupId;

const isFilling = ref(false);

const groups = ref([]);

// 修改数据结构，为每个段创建一个数组  
const segmentDataGroups = ref([
  [], // 第一段数据  
  [], // 第二段数据  
  [], // 第三段数据  
  []  // 第四段数据  
]);

// 给每个弹窗存储对应的数据
const preFilledData = ref([
  { code: '', score: '' },
  { code: '', score: '' },
  { code: '', score: '' },
  { code: '', score: '' }
]);

//给每个按钮添加点击事件，点击后弹出对话框(给初值)
const dialogs = ref([
  { visible: false, title: '第一段' },
  { visible: false, title: '第二段' },
  { visible: false, title: '第三段' },
  { visible: false, title: '第四段' }
]);

const showPopup = ref(false);
const codes = ref([]);
const tableData = ref([]);
const codeToScoreMap = ref({});
const codeToScoreMapcontent = ref({});

const selectedGroupData = ref([]);

const selectedDifficultyId = ref(null);

// 添加一个函数来获取段名
function getSegmentNameByIndex(index) {
  const segmentNames = ['第一段', '第二段', '第三段', '第四段'];
  return segmentNames[index];
}

//查询团队申报的项目以及编码
async function fetchproject() {
  if (!teamId) return;
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/teamproject/project/applicationDetail/${teamId}`, {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('userToken')
      }
    });

    groups.value = response.data.reduce((acc, current) => {
      // 查找是否已经有一个相同 id 的项目
      const existingProjectIndex = acc.findIndex(project => project.id === current.id);

      if (existingProjectIndex !== -1) {
        // 如果找到了，将当前项目添加到该项目的 applicationDetails 数组中
        acc[existingProjectIndex].applicationDetails.push(current);
      } else {
        // 如果没有找到，添加当前项目到累加器数组
        acc.push(current);
      }

      return acc;
    }, []);

    tableData.value = groups.value.map(item => {
      return item.applicationDetails
    })
  } catch (error) {
    console.log('没有找到:', error);
  }
}

onMounted(() => {
  fetchproject();
  fetchCodes();
})

//返回上一步
function soloback() {
  router.back();
}

// 获取编码组信息
async function fetchCodes() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/teamproject/difficultyid/${routineid}`, {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('userToken')
      }
    });
    selectedGroupData.value = response.data.data;

    // 提取 code 和 score
    codeToScoreMap.value = {};
    codes.value = [];
    selectedGroupData.value.forEach(item => {
      codeToScoreMap.value[item.code] = item.score;
      codeToScoreMapcontent.value[item.code] = item.content;
      codes.value.push(item.code);
    });
  } catch (error) {
    console.error('获取编码组信息失败:', error);
  }
}

//汇总需要申报提交的数据
function saveData(segmentIndex) {
  const data = {
    ...preFilledData.value[segmentIndex],
    routineid: routineid // 添加选中的未申报难度的id
  };
  segmentDataGroups.value[segmentIndex].push(data);
  closeDialog(segmentIndex);
  preFilledData.value[segmentIndex].code = '';
  preFilledData.value[segmentIndex].score = '';
  preFilledData.value[segmentIndex].content = '';
  // 用户已经开始填报，更新状态
  isFilling.value = true;
}

//根据code获取score
function getScoreByCode(code) {
  return codeToScoreMap.value[code] || '未知';
}

//根据code获取content
function getScoreByCodecontent(code) {
  return codeToScoreMapcontent.value[code] || '未知';
}


//监听数据变化，根据code更新score
watch(() => preFilledData.value.map(item => item.code),
  (newCodes) => {
    newCodes.forEach((code, index) => {
      if (code) {
        preFilledData.value[index].score = codeToScoreMap.value[code] || '';
      }
    });
  },
  { deep: true, immediate: true }
);

function showRulesDialog() {
  console.log(segmentDataGroups.value);

  showPopup.value = !showPopup.value;
}

function closeRulesDialog() {
  showPopup.value = !showPopup.value;
}

//删除数据方法
function deleteData(segmentIndex, itemIndex) {
  segmentDataGroups.value[segmentIndex].splice(itemIndex, 1);

  // 如果没有剩余数据，重置 isFilling
  if (segmentDataGroups.value.every(segment => segment.length === 0)) {
    isFilling.value = false;
  }
}

// 提交申报难度的数据
async function submitAllData() {
  if (!isFilling.value) {
    ElMessage.warning('请先填报数据');
    return;
  }
  const allData = segmentDataGroups.value.flat();
  if (allData.length > 18) {
    ElMessage.error('数据条目超过 18 条限制');
  return;
  }
  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/difficulty/teamproject/routineid', allData, {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('userToken')
      }
    });
    if (response.status == 200) {
      ElMessage.success('提交成功');
      // 清空所有段的数据
      segmentDataGroups.value = [
        [], // 第一段数据
        [], // 第二段数据
        [], // 第三段数据
        [], // 第四段数据
      ];

      // 重置 preFilledData
      preFilledData.value = [
        { code: '', score: '' },
        { code: '', score: '' },
        { code: '', score: '' },
        { code: '', score: '' }
      ];
      addappliction.value = '';
      projectname.value = '';
      // 重置 isFilling 状态
      isFilling.value = false;
    }
  } catch (error) {
    console.error(error);
    if (error.response && error.response.status === 500) {
      ElMessage.error('服务器内部错误，请稍后再试或联系管理员。');
    } else {
      ElMessage.error('提交失败：' + error.message);
    }
  }
}

//通过获取选中的编码，获取对应的分数
function querySearch(queryString, cb) {
  const results = queryString
    ? codes.value.filter(code => code.toLowerCase().includes(queryString.toLowerCase()))
    : codes.value;
  cb(results);
}

//给不同的段数添加分数和编码
function handleSelect(item, dialogIndex) {
  preFilledData.value[dialogIndex].code = item; // 更新编码
  preFilledData.value[dialogIndex].score = getScoreByCode(item); // 更新分数
  preFilledData.value[dialogIndex].content = getScoreByCodecontent(item) || '';// 更新内容
}

//获取渲染到页面的数据
function checkCodeRisk(dialogIndex) {
  if (preFilledData.value[dialogIndex].code && !codes.value.includes(preFilledData.value[dialogIndex].code)) {
  }
}

//打开填报弹窗
function showDialog(segmentIndex) {
  dialogs.value[segmentIndex].visible = true;
}

//关闭填报弹窗
function closeDialog(dialogIndex) {
  dialogs.value[dialogIndex].visible = false;
}


//格式化申报内容
function replaceCharacters(input) {
  // 找到第一个 '/' 的位置
  const firstSlashIndex = input.indexOf('/');
  if (firstSlashIndex === -1) {
    return input; // 如果没有找到 '/'，直接返回原字符串
  }

  // 找到最后一个 '+' 的位置
  const lastPlusIndex = input.lastIndexOf('+');
  if (lastPlusIndex === -1) {
    return input; // 如果没有找到 '+'，直接返回原字符串
  }

  // 提取第一个 '/' 后的字符
  const firstPart = input.substring(0, firstSlashIndex + 1);
  const middlePart = input.substring(firstSlashIndex + 1, lastPlusIndex);
  const lastPart = input.substring(lastPlusIndex);

  // 将中间部分替换成 '...'
  const result = firstPart + '...' + lastPart;
  return result;
}

</script>

<style scoped>
.container {
  display: flex;
  flex-wrap: wrap;
}

.centered-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  /* 居中对齐 */
}

* {
  box-sizing: border-box;
}

.button-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10px;
}

.el-button {
  margin: 0 10px;
}

.el-button:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.申报规则 {
  margin-left: auto;
}

.submitted-data {
  margin: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px;
  background-color: #f5f7fa;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.submitted-item {
  padding: 8px;
  border-radius: 25px;
  color: white;
  background-color: #409eff;
  margin-bottom: 5px;
  box-shadow: 10px;
}

.submitted-data h3 {
  margin-top: 0;
  font-size: 16px;
  /* 标题字体也可以适当减小 */
}

.segment-container {
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #a3c9c7;
}
</style>